package com.gph.saviorframework.security.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gph.saviorframework.Constants;
import com.gph.saviorframework.FieldType;
import com.gph.saviorframework.common.model.Org;
import com.gph.saviorframework.common.model.Position;
import com.gph.saviorframework.common.model.PositionLevel;
import com.gph.saviorframework.dao.security.OrgDao;
import com.gph.saviorframework.dao.security.PositionDao;
import com.gph.saviorframework.dao.security.PositionLevelDao;
import com.gph.saviorframework.dao.security.RoleDao;
import com.gph.saviorframework.security.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Transactional
public class PositionServiceImpl implements PositionService {

    @Autowired
    private PositionDao positionDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private OrgDao orgDao;

    @Autowired
    private PositionLevelDao positionLevelDao;

    /** 岗位类型:全局 */
    private static final String TYPE_GLOBLE = "0";

    /** 岗位类型:指定机构 */
    private static final String TYPE_ORG = "1";

    /** 岗位类型:指定级别 */
    private static final String TYPE_LEVEL = "2";

    private Map<String, String> fields = new HashMap<String, String>();

    public PositionServiceImpl(){
        fields.put("POSITION_ID", FieldType.STRING);
        fields.put("POSITION_NAME",FieldType.STRING);
    }

    /**
     * 保存岗位和角色的关系
     *
     * @param positionId
     * @param roleIds
     */
    public void savePositionRole(String positionId, String[] roleIds) {
        Object position = get(positionId);
        if (null != position) {
            positionDao.deletePositionRelRole(positionId);
            if(roleIds!=null){
                for (String id : roleIds) {
                    Object role = roleDao.get(id);
                    if (role != null) {
                        positionDao.addPositionRelRole(positionId,id);
                    }
                }
            }
        }
    }

    /**
     * 保存岗位，所选部门和岗位界别的关系
     *
     * @param position
     * @param checkedOrgs
     * @param positionLevels
     */
    public void save(Position position, String[] checkedOrgs, String[] positionLevels) {
        positionDao.save(position);
        if (position.getType().equalsIgnoreCase(TYPE_ORG)) {
            for (String orgId : checkedOrgs) {
                Object org = orgDao.get(orgId);
                if (org != null) {
                    positionDao.addPositionRelOrg(position.getId().toString(),orgId);
                }
            }
        }
        else if (position.getType().equalsIgnoreCase(TYPE_LEVEL)) {
            for (String pl : positionLevels) {
                PositionLevel positionLevel = positionLevelDao.get(pl);
                if (positionLevel != null) {
                    positionDao.addPositionRelPositionLevel(position.getId().toString(),positionLevel.getId());
                }
            }
        }
    }

    /**
     * 更新岗位，所选部门和岗位界别的关系
     *
     * @param position
     * @param checkedOrgs
     * @param positionLevels
     */
    public void update(Position position, String[] checkedOrgs, String[] positionLevels) {
        positionDao.update(position);

        positionDao.deletePositionRelOrg(position.getId().toString());
        positionDao.deletePositionRelPositionLevel(position.getId().toString());

        if (position.getType().equalsIgnoreCase(TYPE_ORG)){
            if(checkedOrgs!=null){
                for (String orgId : checkedOrgs) {
                    Object org = orgDao.get(orgId);
                    if (org != null) {
                        positionDao.addPositionRelOrg(position.getId().toString(),orgId);
                    }
                }
            }
        }
        else if (position.getType().equalsIgnoreCase(TYPE_LEVEL)){
            if(positionLevels!=null){
                for (String pl : positionLevels) {
                    PositionLevel positionLevel = positionLevelDao.get(pl);
                    if (positionLevel != null) {
                        positionDao.addPositionRelPositionLevel(position.getId().toString(),positionLevel.getId());
                    }
                }
            }
        }
    }

    /**
     * 根据组织机构查找
     *
     * @param orgId
     * @return
     */
    public List<Map<String, Object>> findByOrg(String orgId) {
        Org org = orgDao.get(orgId);
        if (org != null){
            return positionDao.findByOrg(orgId,org.getLevel().toString());
        }
        return null;
    }

    @Override
    public String getKey() {
        return positionDao.getKey();
    }

    /**
     * 保存
     *
     * @param position
     */
    public void save(Position position) {
        positionDao.save(position);
    }

    /**
     * 根据编号获取
     *
     * @param id
     * @return
     */
    public Position get(String id) {
        return positionDao.get(id);
    }

    /**
     * 更新
     *
     * @param position
     * @return
     */
    public void update(Position position) {
        positionDao.update(position);
    }

    /**
     * 批量更新
     *
     * @param positions
     */
    @Override
    public void update(Set<Position> positions) {
        for(Position position : positions){
            update(position);
        }
    }

    /**
     * 根据条件返回数据
     *
     * @param sort
     * @param dir
     * @param params
     * @return
     */
    public List<Map<String, Object>> find(String sort, String dir, Map<String, Object> params) {
        return positionDao.find(sort,dir,genWhereClause(params));
    }

    /**
     * 带分页参数的，给bootstrap使用的
     *
     * @param start  开始页码，从1开始
     * @param limit  每页查询的次数
     * @param sort
     * @param dir
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> find(int start, int limit, String sort, String dir, Map<String, Object> params,Object... extras) {
        Map<String,Object> map = new HashMap<String, Object>();

        PageHelper.startPage(start, limit);
        List<Map<String,Object>> list = find(sort, dir, params);
        PageInfo pageInfo = new PageInfo(list);

        map.put(Constants.DEFAULT_RECORD_MODEL_KEY, list);
        map.put(Constants.DEFAULT_COUNT_MODEL_KEY, pageInfo.getPages());
        map.put(Constants.DEFAULT_RECORDS_MODEL_KEY,pageInfo.getTotal());
        map.put(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);

        return map;
    }

    /**
     * 统计数量
     *
     * @param params
     * @return
     */
    public long count(Map<String, Object> params) {
        return positionDao.count(genWhereClause(params));
    }

    /**
     * 根据主键删除
     *
     * @param id
     */
    public void delete(String id) {
        //删除和org之间的关系
        //删除和pl之间的关系
        positionDao.deletePositionRelOrg(id.toString());
        positionDao.deletePositionRelPositionLevel(id.toString());
        positionDao.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    public void deleteByIds(String[] ids) {
        for(String id : ids){
            delete(id);
        }
    }

    /**
     * 查询字段集合
     *
     * @return
     */
    public Map<String, String> getFields() {
        return fields;
    }

    /**
     * 根据id查询map
     *
     * @param id
     * @return
     */
    public Map<String, Object> findById(String id) {
        return positionDao.findById(id);
    }

    /**
     * 生成where条件
     *
     * @param params
     * @param extra
     * @return
     */
    public String genWhereClause(Map<String, Object> params, Object... extra) {
        String whereClause = "1=1";
        if (params!=null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                if (fields.get(key).equals(FieldType.STRING)) {
                    whereClause += " and P." + key + " LIKE '"+params.get(key)+"'";
                } else {
                    whereClause += " and P." + key + " ='"+params.get(key)+"'";
                }
            }
        }
        return whereClause;
    }
}
